<?php
namespace app\yangpay;

use app\yangpay\AopClient;


class AlipayLogic
{

    //支付宝网关地址
    // public $gateway_url = "https://openapi.alipaydev.com/gateway.do";
    public $gateway_url = "https://openapi.alipay.com/gateway.do";

    public $notify_url = '';//异步通知地址

    public $return_url = '';
    //支付宝公钥
    public $alipay_public_key;

    //商户私钥
    public $private_key;

    //应用id
    public $appid;

    //编码格式
    public $charset = "UTF-8";

    public $token = NULL;
    
    //返回数据格式
    public $format = "json";

    //签名方式
    public $signtype = "RSA";

    public function __construct($notify='', $return_url='')
    {

        $this->appid = "2019010962816790";
        $this->private_key = "MIIEowIBAAKCAQEApW8kR84yQ1MQNSrmCiBr1b5toybhYyUa8pvJvzkvuzcQaS4tV6PxcGYQuIGyE2NGpdTvcs28HlPfUgas6xUhvtBCtBWJjl8cOg8A2eZj2x5iTBpidEPv1pkB6LaaZCu5XOksX5tWPE36iOkr7OGv2SEnYBjdF/QBnbviBX4eqj6AccAD4RMm8KTzk/FSQ3yCY5BpHgL9lXKPqlUrYRWtHdCww8DXYxxkmeEWGeE03K/+VLiRNzHgk5+dr1RFyYY3qwHqz0Iv4UNkS2gXIeyufCdewBwp9DBjfbF8IEwLrJdQM7TRZu6HtBfRwZDTXYX+g83A6eInNhyDBBS+7Ro4TQIDAQABAoIBACJMzOTmZ51112Jupotq9XC3rtuo8AoyY0fx7P5syOy0Gf70yAnnv+NiBg17NoS2jKtNXugap+pR0XecUrXbB8gcPfhAjuip55xSCAclsYZ44kCNJ+SbQVrpFnA9i/1A44nT/pNEDbkrIcrJLYZLtL38FcHi5dRVjxA5KD+jSpBZV7S5SDjSzZdi6SKJDGi47NhXP+V7oW4b3xh+Bxu3sNVYa5vJpsFFkp7SqJIgVlxaMJG3HnCh8JH0p2e7tMN767cJN6yC7gP8/NTQFQ6zXdlxjPrcniPA/I6HdAlNZSoYwHh1LEbJ7H8j9IfYIIfCCYuDrwd3JDkCyaYaAvv2tLECgYEA1xA+ysIBomW7bikIIRo0df+yRLuR2tS3u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pHgL9lXKPqlUrYRWtHdCww8DXYxxkmeEWGeE03K/+VLiRNzHgk5+dr1RFyYY3qwHqz0Iv4UNkS2gXIeyufCdewBwp9DBjfbF8IEwLrJdQM7TRZu6HtBfRwZDTXYX+g83A6eInNhyDBBS+7Ro4TQIDAQAB";
        $this->charset = "UTF-8";
        $this->signtype= "RSA2";

        $notify = $notify ? $_SERVER['HTTP_HOST'].'/'.$notify : $_SERVER['HTTP_HOST'].'/alipay/notifyUrl';

        $return_url = $return_url ? 'http://www.dingtaism.com/'.$return_url : 'http://www.dingtaism.com/cherryWeb/index';


        $this->notify_url = $notify;
        $this->return_url = $return_url;

    }
   

    public function pay($data) 
    {

        //商户订单号，商户网站订单系统中唯一订单号，必填
        if ( isset($data['out_trade_no']) == false || empty($data['out_trade_no']) ) {
            $this->error = '商户订单号,不能为空';
            return false;
        }
        //订单名称，必填
        if ( isset($data['subject']) == false || empty($data['subject']) ) {
            $this->error = '订单名称，不能为空';
            return false;
        } 
        //付款金额，必填
        if ( isset($data['total_amount']) == false || empty($data['total_amount']) ) {
            $this->error = '付款金额，不能为空';
            return false;
        } 
        $params['out_trade_no']     = $data['out_trade_no'];
        $params['subject']          = $data['subject'];
        $params['total_amount']     = $data['total_amount'];
        $params['passback_params']  = $data['passback_params'];
        $params['body']         = isset($data['body']) ? $data['body'] : '';
        //超时时间
        $params['timeout_express'] = "2m";
        $params['productCode'] = "QUICK_WAP_PAY";
        $biz_content = json_encode($params,JSON_UNESCAPED_UNICODE);
        // dump($biz_content);die;

        $aop = new AopClient ();

        $aop->gatewayUrl    = $this->gateway_url;
        $aop->appId         = $this->appid;
        $aop->rsaPrivateKey =  $this->private_key;
        $aop->alipayrsaPublicKey = $this->alipay_public_key;
        $aop->apiVersion    ="1.0";
        $aop->postCharset   = $this->charset;
        $aop->format        = $this->format;
        $aop->signType      = $this->signtype;

        $apiParams['notify_url']  = $this->notify_url;
        $apiParams['return_url']  = $this->return_url;
        // $apiParams['return_url']  = $this->return_url;
        $apiParams['biz_content'] = $biz_content;
        // dump($aop->appId);die;
        // 开启页面信息输出
        //$aop->debugInfo=true;
        $result = $aop->pageExecute($apiParams,"post");
        if ($result) return $result;
        // echo $result;
        die;

    }

    /**
     * 验签方法
     * @param $arr 验签支付宝返回的信息，使用支付宝公钥。
     * @return boolean
     */
    function check($arr)
    {
        $aop = new AopClient();
        $aop->alipayPublicKey = $this->alipay_public_key;
        $result = $aop->rsaCheckV1($arr, $this->alipay_public_key, $this->signtype);
        return $result;
    }

}

/**
 * 加密方法
 * @param string $str
 * @return string
 */
 function encrypt($str,$screct_key){
    //AES, 128 模式加密数据 CBC
    $screct_key = base64_decode($screct_key);
    $str = trim($str);
    $str = addPKCS7Padding($str);
    $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128,MCRYPT_MODE_CBC),1);
    $encrypt_str =  mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $screct_key, $str, MCRYPT_MODE_CBC);
    return base64_encode($encrypt_str);
}

/**
 * 解密方法
 * @param string $str
 * @return string
 */
 function decrypt($str,$screct_key){
    //AES, 128 模式加密数据 CBC
    $str = base64_decode($str);
    $screct_key = base64_decode($screct_key);
    $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128,MCRYPT_MODE_CBC),1);
    $encrypt_str =  mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $screct_key, $str, MCRYPT_MODE_CBC);
    $encrypt_str = trim($encrypt_str);

    $encrypt_str = stripPKSC7Padding($encrypt_str);
    return $encrypt_str;

}

/**
 * 填充算法
 * @param string $source
 * @return string
 */
function addPKCS7Padding($source){
    $source = trim($source);
    $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);

    $pad = $block - (strlen($source) % $block);
    if ($pad <= $block) {
        $char = chr($pad);
        $source .= str_repeat($char, $pad);
    }
    return $source;
}
/**
 * 移去填充算法
 * @param string $source
 * @return string
 */
function stripPKSC7Padding($source){
    $source = trim($source);
    $char = substr($source, -1);
    $num = ord($char);
    if($num==62)return $source;
    $source = substr($source,0,-$num);
    return $source;
}
